#!/usr/bin/env python3

import requests
from bs4 import BeautifulSoup
import sys

class TerminalFormatter:
    """处理终端文本样式和颜色的工具类"""
    
    STYLES = {
        "normal": "\033[0m",
        "bold": "\033[1m",
        "italic": "\033[3m"
    }

    COLORS = {
        "black": "\033[30m",
        "red": "\033[31m",
        "green": "\033[32m",
        "yellow": "\033[33m",
        "blue": "\033[34m",
        "magenta": "\033[35m",
        "cyan": "\033[36m",
        "white": "\033[37m",
        "bright_black": "\033[90m",
        "bright_red": "\033[91m",
        "bright_green": "\033[92m",
        "bright_yellow": "\033[93m",
        "bright_blue": "\033[94m",
        "bright_magenta": "\033[95m",
        "bright_cyan": "\033[96m",
        "bright_white": "\033[97m",
    }

    @staticmethod
    def format_text(text, style="normal", color="white", end="\n"):
        """格式化输出文本"""
        style_code = TerminalFormatter.STYLES.get(style, TerminalFormatter.STYLES["normal"])
        color_code = TerminalFormatter.COLORS.get(color, TerminalFormatter.COLORS["white"])
        print(f"{style_code}{color_code}{text}{TerminalFormatter.STYLES['normal']}", end=end)


class YoudaoTranslator:
    """有道词典查询工具"""
    
    BASE_URL = "https://dict.youdao.com/result?word={0}&lang=en"
    HEADERS = {
        'Host': 'dict.youdao.com',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
    }

    def __init__(self, query):
        self.query = query
        self.soup = None
        
    def fetch_data(self):
        """获取网页数据并解析"""
        url = self.BASE_URL.format(self.query)
        response = requests.get(url=url, headers=self.HEADERS)
        self.soup = BeautifulSoup(response.text, "html.parser")
        
    def print_sentence_translation(self):
        """处理句子翻译结果"""
        paragraphs = self.soup.find_all("p", class_="trans-content")
        if paragraphs:
            for p in paragraphs:
                TerminalFormatter.format_text(p.get_text(), color="bright_green")
            return True
        return False
        
    def print_phonetic_notation(self):
        """处理音标/拼音"""
        phonetic_divs = self.soup.find_all("div", class_="phone_con")
        if phonetic_divs:
            for div in phonetic_divs[0].find_all("div", "per-phone"):
                spans = div.find_all("span")
                if len(spans) > 1:
                    TerminalFormatter.format_text(
                        f"{spans[0].get_text()} [{spans[1].get_text()}]",
                        style="italic", color="white"
                    )
                elif spans:
                    TerminalFormatter.format_text(
                        f"[{spans[0].get_text()}]",
                        style="italic", color="white"
                    )
    
    def print_english_word_translation(self):
        """处理英文单词翻译"""
        word_lists = self.soup.find_all("ul", class_="basic")
        if word_lists:
            for li in word_lists[0].find_all("li", "word-exp"):
                spans = li.find_all("span")
                if len(spans) > 1:
                    TerminalFormatter.format_text(
                        f"{spans[0].get_text()} ",
                        style="bold", color="green", end=""
                    )
                    TerminalFormatter.format_text(
                        spans[1].get_text(),
                        color="bright_green"
                    )
                else:
                    TerminalFormatter.format_text(
                        spans[0].get_text(),
                        color="bright_green"
                    )
    
    def print_chinese_word_translation(self):
        """处理中文词语翻译"""
        word_lists = self.soup.find_all("ul", class_="basic")
        if word_lists:
            for i, li in enumerate(word_lists[0].find_all("li", "word-exp-ce mcols-layout"), 1):
                for div in li.find_all("div", "col2"):
                    translation = div.find("div", class_="trans-ce").find("a", class_="point").get_text()
                    explanation = div.find("div", class_="word-exp_tran grey")
                    
                    TerminalFormatter.format_text(
                        f"{i}.{translation}\n ",
                        style="italic", color="bright_green", end=""
                    )
                    if explanation:
                        TerminalFormatter.format_text(
                            f"{explanation.get_text()}\n",
                            style="normal"
                        )
                    else:
                        print("\n")
    
    def print_bilingual_examples(self):
        """处理双语例句"""
        examples_section = self.soup.find_all("div", class_="blng_sents_part dict-module")
        if examples_section:
            TerminalFormatter.format_text("\n双语例句:", style="bold", color="red")
            for i, li in enumerate(examples_section[0].find_all("li", class_="mcols-layout"), 1):
                english = li.find("div", class_="sen-eng").get_text()
                chinese = li.find("div", class_="sen-ch").get_text()
                TerminalFormatter.format_text(
                    f"{i}.{english}",
                    style="italic", color="bright_green"
                )
                TerminalFormatter.format_text(
                    f"{chinese}\n",
                    color="yellow"
                )
    
    def translate(self):
        """执行翻译流程"""
        self.fetch_data()
        
        if self.print_sentence_translation():
            return
            
        self.print_phonetic_notation()
        self.print_english_word_translation()
        self.print_chinese_word_translation()
        self.print_bilingual_examples()


def main():
    if len(sys.argv) < 2:
        print("Usage: yd <word or sentence to translate>")
        sys.exit(1)
        
    query = " ".join(sys.argv[1:])
    translator = YoudaoTranslator(query)
    translator.translate()


if __name__ == "__main__":
    main()